package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            // 每次在远程调用并创建代理对象执行方法之前就会触发拦截器
            @Override
            public void apply(RequestTemplate template) {
                // 1.通过RequestContextHolder拿到老请求
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                        RequestContextHolder.getRequestAttributes();
                if (servletRequestAttributes != null) {
                    HttpServletRequest oldRequest = servletRequestAttributes.getRequest();
                    // 2.同步请求头数据
                    if(oldRequest!=null){
                        String cookie = oldRequest.getHeader("Cookie");
                        template.header("Cookie",cookie);
                    }
                }
            };
        };
    }

}
